//
//  JHRulerView.m
//  iOS尺子控件
//
//  Created by JH on 2017/4/18.
//  Copyright © 2017年 JH. All rights reserved.
//

#import "JHRulerView.h"
#import "JHRulerCell.h"

@interface JHRulerView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic , strong) CAShapeLayer *markLayer;
@property (nonatomic , strong) UICollectionView *collectionView;
@property (nonatomic, assign, readwrite) CGFloat currentValue;//markView指示的值


@end

@implementation JHRulerView

- (instancetype)initWithFrame:(CGRect)frame rulerShowType:(rulerViewShowType)showType{
    self = [super initWithFrame:frame];
    if (self) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        self.rulerStyle.showType = showType;
    if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }else{
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
        self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = self.rulerStyle.backgroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
    if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
            _collectionView.alwaysBounceHorizontal = YES;
    }else{
        _collectionView.alwaysBounceVertical = YES;
    }
    [_collectionView registerClass:[JHRulerCell class] forCellWithReuseIdentifier:[JHRulerCell jh_reuseIdentifier]];
        [self addSubview:self.collectionView];
        
        self.currentValue = self.rulerStyle.minValue;
        [self.layer addSublayer:self.markLayer];
    }
    return self;
}

//- (void)awakeFromNib{
//    [super awakeFromNib];
//    [self setupUI];
//}


- (void)setupUI{
    }


- (void)layoutSubviews{
    [super layoutSubviews];
    
    if (self.rulerType == JHRulerTypePicker) {
        CGRect layerFrame = self.markLayer.frame;
        if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
            //floor向下取整,添加周围添加额外滚动区域
            self.collectionView.contentInset = UIEdgeInsetsMake(0, floor(CGRectGetWidth(self.bounds) / 2), 0, floor(CGRectGetWidth(self.bounds) / 2));//这里如果出现小数貌似会不准，所以特殊处理一下;左右添加额外滚动区域
            layerFrame.origin.x = CGRectGetWidth(self.bounds) / 2 - CGRectGetWidth(layerFrame) / 2;
        }else{
        self.collectionView.contentInset = UIEdgeInsetsMake(floor(CGRectGetHeight(self.bounds) / 2),0, floor(CGRectGetHeight(self.bounds) / 2), 0);//上下添加额外滚动区域
            layerFrame.origin.y = CGRectGetHeight(self.bounds)/2 - CGRectGetHeight(layerFrame)/2;
        }
        //设置contentInset会导致scrollViewDidScroll方法调用，导致self.currentValue变化。。。所以这里要重新设置默认显示的值
        [self updateCurrentValue:self.rulerStyle.defaultVaule animated:NO];
        self.markLayer.frame = layerFrame;
        
    } else {
        if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
            self.collectionView.contentInset = UIEdgeInsetsMake(0, floor(self.rulerStyle.margin), 0, floor(self.rulerStyle.margin));//这里如果出现小数貌似会不准，所以特殊处理一下

        }else{
            self.collectionView.contentInset = UIEdgeInsetsMake(floor(self.rulerStyle.margin), 0,  floor(self.rulerStyle.margin), 0);
        }
    }
}

#pragma mark - CollectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return (self.rulerStyle.maxValue - self.rulerStyle.minValue) / self.rulerStyle.accuracy / 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    JHRulerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[JHRulerCell jh_reuseIdentifier] forIndexPath:indexPath];
    [cell updateUIWithRulerStyle:self.rulerStyle atIndexPath:indexPath];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
        return CGSizeMake(self.rulerStyle.spacing * 10, CGRectGetHeight(collectionView.bounds));
    }else{
        return CGSizeMake(CGRectGetWidth(collectionView.bounds), self.rulerStyle.spacing * 10);
    }
}
#pragma mark - scroller协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.rulerType != JHRulerTypePicker) {
        return;
    }
    

    if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
        CGFloat offsetX = scrollView.contentOffset.x;//左划为正,右划为负
        /**
         scrollView.contentInset.left 为正,屏幕一半大小
         scrollView的偏移量不包括添加的额外滚动区域大小
         */
        self.currentValue = (offsetX + scrollView.contentInset.left) / self.rulerStyle.spacing * self.rulerStyle.accuracy + self.rulerStyle.minValue;
    }else{
        CGFloat offsetY = scrollView.contentOffset.y;
        self.currentValue = (offsetY + scrollView.contentInset.top) / self.rulerStyle.spacing * self.rulerStyle.accuracy + self.rulerStyle.minValue;
    }
    
    if (self.valueChangeCallback) {
        self.valueChangeCallback(self.currentValue);
    }
}


/**
 *  这个方法可以让scrollview刚好停留在整数位置！！！牛逼完了~~
 */
/*
round：如果参数是小数，则求本身的四舍五入。
ceil：如果参数是小数，则求最小的整数但不小于本身.
floor：如果参数是小数，则求最大的整数但不大于本身.
 */
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    //targetContentOffset结构体指针,只能使用->
#pragma mark - ???????????????
    if (self.rulerStyle.stopOnTheLine == YES) {
        CGPoint originTargetContentOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);
        if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
            CGFloat offsetX = originTargetContentOffset.x;
            CGFloat result = round((offsetX + scrollView.contentInset.left) / self.rulerStyle.spacing) * self.rulerStyle.spacing;//四舍五入
            *targetContentOffset = CGPointMake(result - scrollView.contentInset.left, originTargetContentOffset.y);
        }else{
            CGFloat offsetY = originTargetContentOffset.y;
            CGFloat result = round((offsetY + scrollView.contentInset.top)/self.rulerStyle.spacing) * self.rulerStyle.spacing;
            *targetContentOffset = CGPointMake(originTargetContentOffset.x,result - scrollView.contentInset.top);
        }
    }
}










#pragma mark - 懒加载
- (JHRulerStyle *)rulerStyle{
    if (!_rulerStyle) {
        _rulerStyle = [[JHRulerStyle alloc] init];
    }
    return _rulerStyle;
}

- (CAShapeLayer *)markLayer{
    if (!_markLayer) {
        CGSize size = self.rulerStyle.markViewSize;
        _markLayer = [CAShapeLayer layer];
        _markLayer.frame = CGRectMake(0, 0, size.width, size.height);
        UIBezierPath *path = [UIBezierPath bezierPath];
        if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
            [path moveToPoint:CGPointZero];
            [path addLineToPoint:CGPointMake(size.width, 0)];
            [path addLineToPoint:CGPointMake(size.width / 2.0, size.height)];
        }else{
            [path moveToPoint:CGPointZero];
            [path addLineToPoint:CGPointMake(size.width, size.height / 2.0)];
            [path addLineToPoint:CGPointMake(0, size.height)];
        }
        [path closePath];
        _markLayer.path = path.CGPath;
        _markLayer.fillColor = self.rulerStyle.markViewColor.CGColor;
        _markLayer.borderColor = self.rulerStyle.markViewColor.CGColor;
    }
    return _markLayer;
}
- (CGFloat)currentValue{
    if (self.rulerType == JHRulerTypePicker) {
        return _currentValue;
    }else{
        return 0;
    }
}

#pragma mark - 两个共有方法
- (void)reloadData{
    self.collectionView.backgroundColor = self.rulerStyle.backgroundColor;
    [self.collectionView reloadData];
    
    if (self.rulerType == JHRulerTypePicker) {
        self.markLayer.hidden = NO;
        
        [self updateCurrentValue:self.currentValue animated:NO];
        if (!CGSizeEqualToSize(self.rulerStyle.markViewSize, self.markLayer.frame.size)) {
            [self.markLayer removeFromSuperlayer];
            self.markLayer = nil;
            [self.layer addSublayer:self.markLayer];
        }
        self.markLayer.fillColor = self.rulerStyle.markViewColor.CGColor;
        self.markLayer.borderColor = self.rulerStyle.markViewColor.CGColor;
    } else {
        self.markLayer.hidden = YES;
    }
}


- (void)updateCurrentValue:(CGFloat)value animated:(BOOL)animated {
    if (self.rulerType != JHRulerTypePicker) {
        return;
    }
    if (value > self.rulerStyle.maxValue) {
        value = self.rulerStyle.maxValue;
    }
    if (value < self.rulerStyle.minValue) {
        value = self.rulerStyle.minValue;
    }
    self.currentValue = value;
    if (self.rulerStyle.showType == rulerViewshowHorizontalType) {
        CGFloat offsetX = (self.currentValue - self.rulerStyle.minValue) * self.rulerStyle.spacing / self.rulerStyle.accuracy - self.collectionView.contentInset.left;
        [self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:animated];

    }else{
        CGFloat offsetY = (self.currentValue - self.rulerStyle.minValue) * self.rulerStyle.spacing / self.rulerStyle.accuracy - self.collectionView.contentInset.top;
        [self.collectionView setContentOffset:CGPointMake(0, offsetY) animated:animated];
    
    }
}















/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
